import re
import os
import tkinter
import tkinter.messagebox


def start():
    os.remove("./file.txt")

    fp = open("./input.txt", "r", encoding="utf-8")
    content = fp.read(10 * 1024 * 1024)
    fp.close()

    # start = """"""
    # end = """
    # """

    result = re.match(r'# < ?span style="color:#619BE4;?" ?>(.*?)</span ?>', content)
    start = result.group(1)

    result = re.search(r'\*\*\*\*\*(((?!\*\*\*\*\*).)+)$', content, re.S)

    end = result.group(0)

    print(start)
    print("===================================")
    print(end)

    sort_list = re.findall(r'(\*\*\*\*\*.*?)# < ?span style="color:#619BE4;?" ?>(.*?)</span ?>', content, re.S)

    new_list = []
    size = len(sort_list) - 1
    index = 0
    for c in sort_list:
        s = None
        ed = None
        if index == 0:
            new_list.append((start.lower(), c[0]))
        else:
            new_list.append((sort_list[index - 1][1].lower(), c[0]))
        index += 1
    new_list.append((sort_list[-1][1].lower(), end))

    with open("./file.txt", "a", encoding="utf-8") as fp:
        for c in sorted(new_list, key=lambda x: x[0]):
            fp.write(
                ('# <span style="color:#619BE4">{}</span>\n'.format(c[0]) + c[1]).replace("\n\n\n", "\n\n").replace(
                    "color:#619BE4;", "color:#619BE4").replace("</span >", "</span>"))


def run_start():
    try:
        start()
        tkinter.messagebox.showinfo(message="执行完毕")
        os.system("start ./file.txt")
    except Exception as e:
        print(e)
        tkinter.messagebox.showerror(message="出现错误")


root = tkinter.Tk()

start_btn = tkinter.Button(text="开始执行", command=run_start)
start_btn.pack()

tkinter.mainloop()
